package com.example.fragment;

import android.os.Bundle;
import android.view.View;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;

import com.example.fragment.databinding.ActivityMainDynamicBinding;

public class MainDynamicActivity extends AppCompatActivity implements View.OnClickListener {

    private ActivityMainDynamicBinding binding;
    private int fragmentIndex = 0;
    private FragmentManager fragmentManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityMainDynamicBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        fragmentManager = getSupportFragmentManager();
        binding.btnAdd.setOnClickListener(this);
        binding.btnRemove.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        Fragment fragment;
        switch (view.getId()) {
            case R.id.btn_add:
                String fragmentName = String.format(getResources().getString(R.string.fragment_num), ++fragmentIndex);
                fragment = BlankFragment.newInstance(fragmentName);
                // 添加到Activity中
                fragmentManager.beginTransaction()
                        .addToBackStack(null)  // 支持Back回退操作
                        .add(R.id.fragment_container, fragment, "blank")
                        .commit();
                break;
            case R.id.btn_remove:
                fragment = fragmentManager.findFragmentByTag("blank");
                if (fragment != null) {
                    fragmentIndex = fragmentIndex > 0 ? fragmentIndex - 1 : 0;
                    fragmentManager.beginTransaction()
                            .remove(fragment)
                            .commit();
                }
                break;
        }
    }
}